<template>
  <div class="medical-record-audit">
    <el-page-header @back="$router.go(-1)" content="电子病历审核系统" />
    
    <div class="audit-content">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card class="audit-card">
            <template #header>
              <div class="card-header">
                <span>病历数据输入</span>
              </div>
            </template>
            
            <div class="input-section">
              <el-form :model="form" label-position="top">
                <el-form-item label="批次大小">
                  <el-input-number v-model="form.batchSize" :min="1" :max="50" />
                </el-form-item>
                
                <el-form-item label="病历数据 (JSON格式)">
                  <el-input
                    v-model="form.records"
                    type="textarea"
                    :rows="15"
                    placeholder="请输入病历数据，格式如下：
[
  {
    'patient_id': 'A12345678',
    'diagnosis': '高血压',
    'medications': ['降压药A', '降压药B'],
    'report_date': '2023-05-15'
  },
  // 更多病历数据...
]"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="submitAudit" :loading="loading">
                    开始审核
                  </el-button>
                  <el-button @click="fillSampleData">填充示例数据</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card class="result-card">
            <template #header>
              <div class="card-header">
                <span>审核统计</span>
              </div>
            </template>
            
            <div class="statistics-section">
              <el-statistic title="总审核量" :value="statistics.total" />
              <el-statistic title="通过量" :value="statistics.passed" />
              <el-statistic title="通过率" :value="statistics.passRate">
                <template #suffix>%</template>
              </el-statistic>
            </div>
          </el-card>
          
          <el-card class="result-card" style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>审核结果详情</span>
              </div>
            </template>
            
            <div class="result-details">
              <el-table :data="auditResults" stripe style="width: 100%" max-height="400">
                <el-table-column prop="patientId" label="患者ID" width="120" />
                <el-table-column prop="status" label="审核结果" width="80">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === '通过' ? 'success' : 'danger'">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="details" label="详情" />
              </el-table>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)

const form = reactive({
  batchSize: 10,
  records: ''
})

const statistics = reactive({
  total: 0,
  passed: 0,
  passRate: 0
})

const auditResults = ref([])

const fillSampleData = () => {
  form.records = JSON.stringify([
    {
      "patient_id": "A12345678",
      "diagnosis": "高血压",
      "medications": ["降压药A", "降压药B"],
      "report_date": "2023-05-15"
    },
    {
      "patient_id": "B87654321",
      "diagnosis": "糖尿病",
      "medications": ["胰岛素"],
      "report_date": "2023-05-16"
    },
    {
      "patient_id": "C1234567",  // 错误：ID不足8位数字
      "diagnosis": "感冒",
      "medications": ["感冒药"],
      "report_date": "2023-05-17"
    },
    {
      "patient_id": "D12345678",
      "diagnosis": "",  // 错误：诊断结果为空
      "medications": ["维生素"],
      "report_date": "2023-05-18"
    },
    {
      "patient_id": "E12345678",
      "diagnosis": "胃炎",
      "medications": ["胃药"],
      "report_date": "2023-13-45"  // 错误：日期格式不正确
    }
  ], null, 2)
}

const submitAudit = async () => {
  if (!form.records) {
    ElMessage.warning('请输入病历数据')
    return
  }
  
  try {
    // 解析病历数据
    const records = JSON.parse(form.records)
    
    loading.value = true
    
    // 调用后端API进行审核
    const response = await request.post('/iterator/audit/', {
      batch_size: form.batchSize,
      records: records
    })
    
    const data = response.data
    
    if (data && data.code === 0) {
      // 更新统计信息
      statistics.total = data.data.total
      statistics.passed = data.data.passed
      statistics.passRate = data.data.pass_rate
      
      ElMessage.success('审核完成')
      
      // 获取详细的审核结果
      await fetchAuditDetails(records)
    } else {
      ElMessage.error(data?.msg || '审核失败')
    }
  } catch (error) {
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data.msg || '审核失败')
    } else {
      ElMessage.error('审核失败：' + error.message)
    }
  } finally {
    loading.value = false
  }
}

const fetchAuditDetails = async (records) => {
  // 模拟审核结果详情（实际应该从后端获取）
  auditResults.value = records.map(record => {
    // 简单的本地验证来模拟后端审核结果
    const errors = []
    
    // 验证患者ID
    if (!record.patient_id || !/^[A-Za-z]\d{8}$/.test(record.patient_id)) {
      errors.push("患者ID格式不正确，应为字母+8位数字")
    }
    
    // 验证诊断结果
    if (!record.diagnosis || !record.diagnosis.trim()) {
      errors.push("诊断结果不能为空")
    }
    
    // 验证日期格式
    if (!record.report_date || !/^\d{4}-\d{2}-\d{2}$/.test(record.report_date)) {
      errors.push("检查报告日期格式不正确，应为YYYY-MM-DD")
    } else {
      const date = new Date(record.report_date)
      if (isNaN(date.getTime())) {
        errors.push("检查报告日期格式不正确，应为YYYY-MM-DD")
      }
    }
    
    const isValid = errors.length === 0
    
    return {
      patientId: record.patient_id,
      status: isValid ? '通过' : '不通过',
      details: isValid ? '审核通过' : errors.join('; ')
    }
  })
}
</script>

<style scoped>
.medical-record-audit {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.audit-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-section {
  padding: 20px 0;
}

.statistics-section {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20px 0;
}

.result-details {
  padding: 10px 0;
}
</style>